package com.hpin.fansea.sale;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.hpin.fansea.R;
import com.hpin.fansea.adapter.AddressAdapter;
import com.hpin.fansea.base.BaseActivity;
import com.hpin.fansea.bean.Address;
import com.hpin.fansea.bean.AddressInfo;
import com.hpin.fansea.bean.ResultBaseBean;
import com.hpin.fansea.swipe.SwipeMenu;
import com.hpin.fansea.swipe.SwipeMenuCreator;
import com.hpin.fansea.swipe.SwipeMenuItem;
import com.hpin.fansea.swipe.SwipeMenuListView;
import com.hpin.fansea.utils.CommonUtils;
import com.hpin.fansea.utils.Constant;
import com.hpin.fansea.utils.DensityUtil;
import com.hpin.fansea.utils.HttpUtil;
import com.hpin.fansea.utils.LogUtil;
import com.lidroid.xutils.http.RequestParams;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 收货地址
 * Created by Aaron on 15/10/23.
 */
public class ChooseReceiveAddressActivity extends BaseActivity {

    private SwipeMenuListView lv_address;
    private TextView tv_add_address;
    private List<Address> addressLists = new ArrayList<Address>();
    private AddressAdapter adapter;
    /**
     * 记录的上一个选中的点  选中下一个点时要把该seleced 设为false 不然listview会乱
     */
    private int lastSelect = -1;

    private boolean hasDefaultAddress;
    /**
     * 小区地址 (北京*爱这城)
     */
    private String communityAddress;
    private TextView tv_right;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_choose_address);

        //网络获取用户地址
        getAddressData();

        initWidget();

    }

    private void initWidget() {

        ImageView iv_left = (ImageView) findViewById(R.id.iv_left);

        TextView tv_title = (TextView) findViewById(R.id.tv_title);

        tv_title.setText(R.string.goods_address);

        tv_right = (TextView) findViewById(R.id.tv_right);
        tv_right.setText(R.string.edit_address);

        iv_left.setOnClickListener(this);
        tv_right.setOnClickListener(this);


        lv_address = (SwipeMenuListView) findViewById(R.id.lv_address);

//        if (userInfo!=null) {
//            communityAddress = userInfo.getCityName() + userInfo.getCommunityName();
//        }
        communityAddress = sp.getString(Constant.cityName, "") + sp.getString(Constant.communityName, "");

        adapter = new AddressAdapter(this, addressLists, communityAddress);
        lv_address.setAdapter(adapter);

        SwipeMenuCreator creator = new SwipeMenuCreator() {

            @Override
            public void create(SwipeMenu menu) {
                // create "open" item
                SwipeMenuItem openItem = new SwipeMenuItem(
                        getApplicationContext());
                // set item background
                openItem.setBackground(new ColorDrawable(Color.rgb(0xC9, 0xC9,
                        0xCE)));
                // set item width
                openItem.setWidth(DensityUtil.dip2px(ChooseReceiveAddressActivity.this, 90));
                // create "delete" item
                SwipeMenuItem deleteItem = new SwipeMenuItem(
                        getApplicationContext());
                // set item background
                deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9,
                        0x3F, 0x25)));
                // set item width
                deleteItem.setWidth(DensityUtil.dip2px(ChooseReceiveAddressActivity.this, 90));
                // set a icon
                deleteItem.setIcon(R.mipmap.ic_delete);
                // add to menu
                menu.addMenuItem(deleteItem);
            }
        };
        // set creator
        lv_address.setMenuCreator(creator);

        /**
         * 条目点击监听
         */
        lv_address.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int position,
                                    long arg3) {

                //如果右上角是 编辑 字的话则跳转到支付页面
                if ("编辑".equals(tv_right.getText().toString().trim())) {
                    if (addressLists != null && addressLists.size() > 0) {
//						lastSelect = position;
                        Intent data = new Intent();
                        data.putExtra("realName", addressLists.get(position).receiver);
                        //小区地址 + 用户填写的地址
                        //认证用户设置收件地址

                        data.putExtra("realAddress", CommonUtils.isNull(sp.getString(Constant.address, "")) ? addressLists.get(position).address :
                                sp.getString(Constant.cityName, "") + sp.getString(Constant.communityName, "") + sp.getString(Constant.address, ""));

//                        data.putExtra("realAddress", userInfo == null ? addressLists.get(position).address :
//                                userInfo.getCityName() + userInfo.getCommunityName() + addressLists.get(position).getAddress());
                        data.putExtra("realTel", addressLists.get(position).contactWay);
                        setResult(4, data);
                        finish();
                    }
                }

                //如果右上角是 完成 的话则调到编辑页面
                if ("完成".equals(tv_right.getText().toString().trim())) {

                    if (addressLists != null && addressLists.size() > 0) {

                        //改变选中的条目的图标
                        addressLists.get(lastSelect).isSelect = false;
                        addressLists.get(position).isSelect = true;
                        lastSelect = position;
                        adapter.notifyDataSetChanged();

                        Intent editIntent = new Intent(ChooseReceiveAddressActivity.this, PurchaseAddressActivity.class);
                        editIntent.putExtra("address", addressLists.get(lastSelect));
                        editIntent.putExtra("hasDefaultAddress", hasDefaultAddress);

                        startActivity(editIntent);

                    }

                }

            }
        });

        /**
         * 删除 监听
         */
        lv_address.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {

                deleteAddress(position);

                return false;
            }

        });

        tv_add_address = (TextView) findViewById(R.id.tv_add_address);
        tv_add_address.setOnClickListener(this);
    }

    private void getAddressData() {

        HttpUtil.getInstance().setGetRequest("获取中...", this, Constant.WEB_ROOT + Constant.GET_ADDRESSES + "?token=" +
                sp.getString(Constant.token, "") + "&pageSize=20&pageIndex=0", new HttpUtil.SuccessListener() {
            @Override
            public void setOnSuccessListener(String str) {
                handleResult(str);
            }
        }, null);

    }

    /**
     * 处理地址结果
     *
     * @param result
     */
    protected void handleResult(String result) {

        try {

            AddressInfo addressInfo = JSONObject.parseObject(result, AddressInfo.class);

            if (Constant.STATUS_SUCESS.equals(addressInfo.status)) {

                addressLists = addressInfo.result;

                if (addressLists != null && addressLists.size() > 0) {
                    if (adapter != null) {

                        for (Iterator<Address> it = addressLists.iterator(); it.hasNext(); ) {
                            Address address = it.next();
                            if (address.isDefault == 1) {
                                addressLists.remove(address);
                                addressLists.add(0, address);
                                lastSelect = 0;
                                hasDefaultAddress = true;

                                saveAddressInfo(address);

                                break;
                            }
                        }

                        //如果没有默认的地址 则设置第一个为点中的状态
                        if (lastSelect == -1) {
                            hasDefaultAddress = false;
                        }
                        lastSelect = 0;
                        addressLists.get(0).isSelect = true;//前面的勾号 选中状态

                        adapter.setAddressLists(addressLists);
                        adapter.notifyDataSetChanged();
                    }
                }

            } else {
                showToast(addressInfo.message);
            }

        } catch (Exception e) {
            e.printStackTrace();
            LogUtil.d("address", "json 文件解析错误~");
        }
    }


    /**
     * 保存地址信息到手机中
     */
    private void saveAddressInfo(Address address) {

        //如果是默认地址则存储到sp中
//        if (mSharedPreferences!=null) {
        SharedPreferences.Editor edit = sp.edit();
        edit.putString(Constant.DEFAULT_PEOPLE, address.receiver);
        edit.putString(Constant.DEFAULT_ADDRESS, communityAddress + address.address);
        edit.putString(Constant.DEFAULT_TEL, address.contactWay);
        edit.commit();
//        }
    }

    /**
     * 删除条目
     *
     * @param position
     */
    private void deleteAddress(final int position) {
        RequestParams params = new RequestParams();
        params.addBodyParameter("token", Constant.token);
        if (addressLists != null) {
            params.addBodyParameter("addressId", addressLists.get(position).id_);
        }

        HttpUtil.getInstance().setPostRequest("获取中...", this, Constant.WEB_ROOT + Constant.DELETE_ADDRESS, params, new HttpUtil.SuccessListener() {
            @Override
            public void setOnSuccessListener(String str) {

//                if (responseInfo != null && !TextUtils.isEmpty(responseInfo.result)) {
                handleDeleteResult(str, position);
//                }

            }
        }, null);

    }

    /**
     * 处理删除的数据
     *
     * @param result
     * @param position
     */
    protected void handleDeleteResult(String result, int position) {
        try {
            ResultBaseBean simpleResult = JSONObject.parseObject(result, ResultBaseBean.class);
            if (simpleResult != null && Constant.STATUS_SUCESS.equals(simpleResult.status)) {

                addressLists.remove(position);
                adapter.setAddressLists(addressLists);
                adapter.notifyDataSetChanged();

            } else {
                showToast(simpleResult.message);
            }

        } catch (Exception e) {
            e.printStackTrace();
            showToast("删除失败");
        }

    }

    @Override
    public void widgetClick(View v) {

        switch (v.getId()) {

            case R.id.iv_left://返回

                finish();

                break;
            case R.id.tv_right://编辑

                if ("编辑".equals(tv_right.getText().toString().trim())) {

                    tv_right.setText("完成");
                    //前面打勾去掉
                    if (addressLists != null && addressLists.size() > 0 && adapter != null) {

                        addressLists.get(0).isSelect = false;
                        adapter.setAddressLists(addressLists);
                        adapter.notifyDataSetChanged();
                    }

                } else if ("完成".equals(tv_right.getText().toString().trim())) {
                    tv_right.setText("编辑");
//				//前面打勾加上
//				if (addressLists!= null && addressLists.size() > 0 && adapter!=null) {
//
//					addressLists.get(0).setSelect(true);
//					adapter.setAddressLists(addressLists);
//					adapter.notifyDataSetChanged();
//				}
                }

                break;
            case R.id.tv_add_address://新建地址

                Intent intent = new Intent(ChooseReceiveAddressActivity.this, PurchaseAddressActivity.class);
                intent.putExtra("hasDefaultAddress", hasDefaultAddress);
                startActivity(intent);

                break;

            default:
                break;
        }

    }

}
